/* eslint-disable react/jsx-indent */
/* eslint-disable no-nested-ternary */
import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { exportQAHistories } from '@/services/download';
import qs from 'qs';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { routerRedux } from 'dva/router';
import {
  Card,
  Row,
  Col,
  Form,
  Input,
  Button,
  message,
  Icon,
  Checkbox,
  Table,
  Tag,
  Select,
  Modal,
  Radio,
  Spin,
  Upload,
  Tabs,
  Drawer,
  Tooltip,
  Pagination,
} from 'antd';
import Custom from './custom.js';
// import Service from '@/modules/service/index'
import Service from '../../../modules/service';
import deleteimg from '@/assets/buttonimg/delete.png';
import useimg from '@/assets/buttonimg/use.png';

const { TabPane } = Tabs;
const FormItem = Form.Item;
const Search = Input.Search;
const InputGroup = Input.Group;
import styles from './index.less';

const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
import pen from '../../../assets/icons/bi.png';
import ljx from '../../../assets/icons/垃圾箱.png';
import xiazi from '@/assets/basic/customDictionary/xiazi.png';
import moreImg from '@/assets/knowledge/more.png';
import moveImg from '@/assets/knowledge/move.png';
import sy from '@/assets/basic/customDictionary/sy.png';
import bianji from '@/assets/basic/customDictionary/bianji.png';
import edit from '@/assets/basic/customDictionary/edit.png';
import qdbuttom from '@/assets/account/robotSetup/qdbuttom.png';
import qxbuttom from '@/assets/account/robotSetup/qxbuttom.png';

class CustomNew extends Component {
  state = {
    dictType: '',
    page: 1,
    limit: 10,
    dictNames: '',
    listA: [],
    totalA: '',
    login: true,
    showModel1: false,
    showModel2: false,
    formatC: '',
    close: false,
  };

  componentDidMount() {
    this.fetch();
  }

  // 主页列表
  fetch = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    console.log(currentUser);
    const { dictType, page, limit, dictNames } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customDictionary/fetch',
        payload: { page, limit, query: dictNames },
        callback: res => {
          console.log('列表数据', res);
          // res.list.map((item, index) => {
          //   item['key'] = index
          // })
          this.props.totalAHome(res.total);
          this.setState({
            listA: res.list,
            totalA: Number(res.total),
            login: false,
          });
        },
      });
    });
  };

  // 主页增加
  coreWordOne = () => {
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    this.props.form.validateFields((err, values) => {
      // 校验方法
      let userInfo = this.props.form.getFieldsValue(); // 获取数据
      if (!err) {
        console.log(userInfo);
        let obj;
        if (userInfo.dictionaryTypes === '1') {
          obj = true;
        }
        if (userInfo.dictionaryTypes === '2') {
          obj = false;
        }
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'customDictionary/fetchc',
            payload: { dictName: userInfo.corewordone, isEnum: obj },
            callback: res => {
              console.log('主页增加内容', res);
              if (res.code === 0) {
                message['success'](`${res.msg}`);
                this.setState(
                  {
                    showModel1: false,
                    formatC: '',
                  },
                  () => {
                    this.props.form.setFields({ corewordone: '' });
                    this.fetch();
                  },
                );
              }
              if (res.status === false) {
                // message['error'](`${res.msg}`)
              }
            },
          });
        });
      }
    });
  };

  // 子页面修改内容
  enumeration = () => {
    this.props.form.setFields({ coreword: '' });
    this.props.form.setFields({ synonym: '' });
    this.setState({
      formatA: '',
      formatB: '',
      showModel2: true,
      itemId: '',
    });
  };

  // 主页添加内容
  addContent = () => {
    this.setState({
      showModel1: true,
    });
  };

  handleDeleteAxios = item => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customDictionary/fetchd',
        payload: { id: item.id },
        callback: res => {
          console.log('componentWillMount', res);
          if (!res.code) {
            message.success(`${res.msg}`);
          }
          this.fetch();
        },
      });
    });
  };

  // 主页删除
  handleDeletes = item => {
    console.log('item', item);
    if (item.isUse) {
      Modal['confirm']({
        title: '删除任务',
        content: '该自定义实体正在被使用中，删除后将影响机器人的正常问答，是否确定删除',
        okText: '删除',
        cancelText: '取消',
        onOk: () => {
          this.handleDeleteAxios(item);
        },
        onCancel() {
          console.log('onCancel');
        },
      });
    } else {
      Modal['confirm']({
        title: '删除任务',
        content: '是否确定删除该实体？',
        okText: '删除',
        cancelText: '取消',
        onOk: () => {
          this.handleDeleteAxios(item);
        },
        onCancel() {
          console.log('onCancel');
        },
      });
    }
  };

  handleDelete = item => {
    console.log('item', item);
    const { dispatch } = this.props;
    if (item.isEnum) {
      // 可枚举
      dispatch(
        routerRedux.push({
          pathname: '/basic/customDictionary/enumerable',
          params: { id: item },
        }),
      );
    }
    if (item.isEnum === false) {
      // 不可枚举
      dispatch(
        routerRedux.push({
          pathname: '/basic/customDictionary/noEnumerationNew',
          params: { id: item },
        }),
      );
    }
  };

  inSue = item => {
    // basicDictSlotList
    // const { dispatch, currentUser } = this.props;
    // this.reqRef = requestAnimationFrame(() => {
    //   dispatch({
    //     type: 'customDictionary/basicDictSlotList',
    //     payload: { id:item.id,page:1,limit:99999 },
    //     callback: res => {
    //       console.log('主页增加内容', res);

    //     },
    //   });
    // });
    console.log(item);
    this.setState({ item: item }, () => {
      this.openClose();
    });
  };

  openClose = () => {
    this.setState({ close: true });
  };

  onClose = () => {
    this.setState({
      close: false,
    });
  };

  callback = key => {
    console.log(key);
  };

  onChangeA = val => {
    // 页数选择
    console.log(val);
    this.setState(
      {
        page: val,
      },
      () => {
        this.fetch();
      },
    );
  };

  // 每页显示多少条数据
  onShowSizeChangeA = (current, pageSize) => {
    console.log('1', current, '2', pageSize);
    this.setState(
      {
        page: current,
        limit: pageSize,
      },
      () => {
        this.fetch();
      },
    );
  };

  Tooltipzdy = () => {
    return (
      <div>
        {`添加实体`}
        <span style={{ marginLeft: 12, paddingTop: 3 }}>
          <Tooltip
            placement="top"
            title="实体名称是一类核心词的总称，如核心词是中国银行、邮政银行、建设银行、招商银行等，那实体名称就可以写成银行类型。"
            arrowPointAtCenter
          >
            <Icon style={{ fontSize: 14 }} type="info-circle"/>
          </Tooltip>
        </span>
      </div>
    );
  };

  onCloses = () => {
    this.props.form.setFields({ corewordone: '' });
    this.setState({
      showModel1: false,
    });
  };

  // eslint-disable-next-line react/sort-comp
  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        // 文字
        xs: 24,
        sm: 4,
        md: 2,
      },
      wrapperCol: {
        // 输入框
        xs: 24,
        sm: 20,
        md: 20,
      },
    };
    const columns = [
      {
        title: '实体名称',
        width: 'calc(30vw)',
        dataIndex: 'name', //返回的索引值
      },
      {
        title: '实体类型',
        width: 'calc(30vw)',
        dataIndex: 'isEnum',
        render(sex) {
          return sex === true ? '可枚举类型' : '不可枚举类型';
        },
      },
      {
        title: '操作',
        dataIndex: 'sex',
        align: 'center',
        width: '250px',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <div className={styles.tool}>
                {item.isUse === true ? (
                  <img
                    onClick={text => {
                      this.inSue(item);
                    }}
                    src={sy}
                    alt="sy"
                  />
                ) : (
                  <span>&#12288;&#12288;&#12288;&#12288;&#12288;</span>
                )}

                <img
                  onClick={text => {
                    this.handleDelete(item);
                  }}
                  src={bianji}
                  alt="bianji"
                />
                <img
                  onClick={text => {
                    this.handleDeletes(item);
                  }}
                  style={{ marginLeft: 15 }}
                  src={edit}
                />
              </div>
              <img src={moreImg} className={styles.more}/>
            </div>
          );
        },
      },
    ];

    return (
      <div>
        <div>
          <img
            style={{ position: 'relative', top: 8, cursor: 'pointer', marginLeft: 12 }}
            onClick={this.addContent}
            src={xiazi}
          />
          {/* <span className='zdyButtonA' style={{ width: 90 }}><Button type='primary'   icon="plus">添加</Button></span> */}
          <span style={{ float: 'right', marginRight: 23 }} className="zdyinputa">
            <Search
              placeholder="请输入搜索内容"
              onSearch={value => {
                console.log(value);
                this.setState({ dictNames: value, page: 1 }, () => {
                  this.fetch();
                });
              }}
              style={{ height: 45, width: 312 }}
            />
          </span>
        </div>
        <div style={{ marginTop: 20 }}>
          <Spin spinning={this.state.login}>
            <div>
              <div className={styles.dabj} style={{ padding: '0px 20px' }}>
                <div className={styles.border} style={{ padding: '0px 0px 1px 1px' }}>
                  <Table
                    className="zdyTable"
                    columns={columns}
                    dataSource={this.state.listA} //数据
                    pagination={false}
                  />
                </div>
              </div>
            </div>

          </Spin>
          <Pagination
            style={{ textAlign: 'center', marginTop: 20, marginBottom: 20 }}
            total={this.state.totalA}
            pageSize={this.state.limit} // 显示几条一页
            current={this.state.page} // 当前页
            showSizeChanger={true} // 是否显示可以设置几条一页的选项
            onChange={this.onChangeA}
            onShowSizeChange={this.onShowSizeChangeA}
            showTotal={() => `共 ${this.state.totalA} 条`}
          />
        </div>

        <Drawer
          className="zdyset"
          title={
            <span onClick={this.onCloses} style={{ cursor: 'pointer' }}>
                <Icon type="arrow-left" style={{ marginRight: 20 }}/>
              添加实体
            </span>
          }
          placement="right"
          closable={false}
          onClose={this.onCloses}
          visible={this.state.showModel1}
          width="calc(100vw - 245px)"
          destroyOnClose
        >
          <div className={styles.der}>
            <Form className="zdyfroma" layout="horizontal">
              <FormItem label="实体名称" onSubmit={this.coreWordOne}>
                {getFieldDecorator('corewordone', {
                  initialValue: `${this.state.formatC}`,
                })(<Input/>)}
              </FormItem>
              <FormItem label="实体类型" {...FormItemLayont}>
                {getFieldDecorator('dictionaryTypes', {
                  initialValue: '1',
                })(
                  <RadioGroup>
                    <div className={styles.newline}>
                      <Radio value="1">
                        <FormattedMessage id="app.customDictionary.enumerable-type"/>
                      </Radio>
                      <span style={{ color: '#cccccc' }}>
                        <FormattedMessage id="app.customDictionary.enumerable-typetext"/>
                      </span>
                      <Radio value="2">
                        <FormattedMessage id="app.customDictionary.noenumerable-type"/>
                      </Radio>
                      <span style={{ color: '#cccccc' }}>
                        <FormattedMessage id="app.customDictionary.noenumerable-typetext"/>
                      </span>
                    </div>
                  </RadioGroup>,
                )}
              </FormItem>
            </Form>
            <div className={styles.flex}>
              <div>
                {/*<img onClick={this.onClose} src={qxbuttom} style={{ marginRight: 50 }} />*/}
                <img onClick={this.coreWordOne} src={qdbuttom}/>
              </div>
            </div>
          </div>
        </Drawer>
        {/* <Modal
          className="modelZdy"
          title={this.Tooltipzdy()}
          visible={this.state.showModel1}
          okText={<FormattedMessage id="app.customDictionary.save" />}
          cancelText={<FormattedMessage id="app.customDictionary.cancel" />}
          onCancel={() => {
            this.props.form.setFields({ corewordone: '' });
            this.setState({
              showModel1: false,
            });
          }}
          onOk={this.coreWordOne} // 确定方法开出去
        >
          <Form layout="horizontal">
            <FormItem label="实体名称" onSubmit={this.coreWordOne} {...FormItemLayont}>
              {getFieldDecorator('corewordone', {
                initialValue: `${this.state.formatC}`,
              })(<Input />)}
            </FormItem>
            <FormItem label="实体类型" {...FormItemLayont}>
              {getFieldDecorator('dictionaryTypes', {
                initialValue: '1',
              })(
                <RadioGroup>
                  <div className={styles.newline}>
                    <Radio value="1">
                      <FormattedMessage id="app.customDictionary.enumerable-type" />
                    </Radio>
                    <span style={{ color: '#cccccc' }}>
                      <FormattedMessage id="app.customDictionary.enumerable-typetext" />
                    </span>
                    <Radio value="2">
                      <FormattedMessage id="app.customDictionary.noenumerable-type" />
                    </Radio>
                    <span style={{ color: '#cccccc' }}>
                      <FormattedMessage id="app.customDictionary.noenumerable-typetext" />
                    </span>
                  </div>
                </RadioGroup>
              )}
            </FormItem>
          </Form>
        </Modal> */}
        <Drawer
          title="词典使用情况"
          placement="right"
          closable
          onClose={this.onClose}
          visible={this.state.close}
          width={800}
          destroyOnClose
        >
          <Service item={this.state.item}/>
        </Drawer>
      </div>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(CustomNew));
